<?php

namespace App\Http\Controllers\admin;

use App\Http\Model\RolePermission;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\View;

/**
 * Class AdminPlatformController 后台基础控制器
 * @package App\Http\Controllers\admin
 */
class AdminPlatformController extends Controller
{
    /** 属性声明 */
    protected $per_list = array();

    /** 方法声明 */
    /**
     * 后台初始化数据方法
     */
    public function __construct(Route $route){
        $action = $route -> getActionName();

        /** 分析路由action信息 */
        $action = ltrim(strchr($action,'@'),'@');

        /** 进行权限验证 */
//        if(!$this -> checkPermisson($action)){
//            echo '<h1 style="text-algin:center;">没有权限</h1>';
//            echo '<a href="/manager/main">返回首页</a>';
//            die;
//        }
        $this -> admin_init();
    }

    /**
     * 权限验证
     */
    public function checkPermisson($action)
    {
        /** 路由权限action过滤集合 */
        $unfilter_action_list = [
            'index', 'main', 'top', 'menu','login','logOut','captcha'
        ];

        /** action过滤 */
        if (in_array($action, $unfilter_action_list)) {
            return true;
        }

        /** token数据通过 */
        $input = Input::all();
        if(isset($input['_token'])){
            return true;
        }

        /** 获取当前管理员角色及权限 */
        $user = session('member');
        if (is_object($user)) {
            $role = $user->role;
            /** 获取当前管理员权限 */
            $permisson_list = RolePermission::where('rid', $role)
                ->select('per_mark')
                ->leftJoin('permission', 'role_permission.pid', '=', 'permission.per_id')
                ->get();
            foreach ($permisson_list as $p) {
                $this->per_list[] = $p->per_mark;
            }

            if (!in_array($action, $this->per_list)) {
                return false;
            }
            return true;
        }
    }

    /**
     * 数据初始化
     */
    protected function admin_init(){
        //1.设置字符集
        header('content-type:text/html;charset=utf-8');
    }

    /**
     * ajax文件上传处理
     */
    public function upload()
    {
        $file = Input::file('Filedata');
        if($file -> isValid()){
            //获取上传文件后缀
            $entension = $file -> getClientOriginalExtension();
            //文件重命名
            $newName = date('YmdHis').mt_rand(100,999).'.'.$entension;
            //创建日期目录
            $dir_name = date('Ymd');
            //移动文件
            $path = $file -> move('uploads/'.$dir_name,$newName);
            $filepath = 'uploads/'. $dir_name . '/' . $newName;
            return $filepath;
        }
    }
}
